package com.controller.api;

import com.biz.*;
import com.controller.backend.BaseController;
import com.core.Result;
import com.core.ResultGenerator;
import com.entity.model.*;
import com.entity.vo.BillListVO;
import com.util.CalendarUtil;
import com.util.PayUtil;
import com.util.webpage.PageData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import tk.mybatis.mapper.entity.Condition;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.util.CalendarUtil.getAddDays;

/**
 * Created by jc on 2019/11/16.
 */
@RestController("apiHotelReservationController")
@RequestMapping("/api/hotelReservation")
public class HotelReservationController extends BaseController<HotelReservation> {
    @Autowired
    private HotelReservationBiz hotelReservationBiz;

    @Autowired
    private BillBiz billBiz;

    @Autowired
    private HotelHomeBiz hotelHomeBiz;

    @Autowired
    private CustomerBiz customerBiz;

    @Autowired
    private SysConfigBiz sysConfigBiz;


    //订房
    @RequestMapping(value = "/bookRoom")
    public Result bookRoom(HotelReservation hotelReservation, @RequestParam String startDate, @RequestParam String endDate) throws Exception {
        if (hotelReservation.getCustomerId() == null) {
            return ResultGenerator.genFailResult("用户编号不能为空");
        }
        if (org.apache.commons.lang3.StringUtils.isBlank(startDate) || org.apache.commons.lang3.StringUtils.isBlank(endDate)) {
            return ResultGenerator.genFailResult("请选择入住时间与离店时间");
        }
        Customer customer = customerBiz.findBy("userId", hotelReservation.getCustomerId());
        if (customer == null) {
            return ResultGenerator.genFailResult("用户不存在");
        } else {

            //用户查询订单 首先将当前用户 状态未过期的订单更新为已过期订单
            Map cond = new HashMap();
            cond.put("customerId", hotelReservation.getCustomerId());
            billBiz.delExpiredBillByCustomerId(cond);

            Condition condition = new Condition(Bill.class);
            condition.createCriteria().andEqualTo("billType", 0).andEqualTo("customerId", customer.getId()).andEqualTo("status", 0);
            List<Bill> billList = billBiz.findByCondition(condition);
            if (billList.size() > 0) {
                return ResultGenerator.genFailResult("您已有待支付的行程,支付完成或取消订单后才能再次订房");
            }

            condition = new Condition(Bill.class);
            condition.createCriteria().andEqualTo("billType", 0).andEqualTo("customerId", customer.getId()).andGreaterThan("status", 0).andLessThan("status", 3);
            billList = billBiz.findByCondition(condition);
            if (billList.size() > 0) {
                return ResultGenerator.genFailResult("您已有未完成的行程,入住完成后才能再次订房");
            }

            condition = new Condition(Bill.class);
            condition.createCriteria().andEqualTo("billType", 0).andEqualTo("customerId", customer.getId()).andEqualTo("status", 4).andGreaterThan("createTime", CalendarUtil.getToday());
            billList = billBiz.findByCondition(condition);
            if (billList.size() > 2) {
                return ResultGenerator.genFailResult("今日您已取消订单3次,请明日再试");
            }


            Condition condition2 = new Condition(HotelReservation.class);
            condition2.createCriteria().andEqualTo("homeId", hotelReservation.getHomeId()).andEqualTo("reserveStartTime", startDate + " 14:00:00").andEqualTo("status", 1);
            List<HotelReservation> list = hotelReservationBiz.findByCondition(condition2);
            HotelHome hotelHome = hotelHomeBiz.findById(hotelReservation.getHomeId());
            if (hotelHome.getIsOpen() == 1) {
                return ResultGenerator.genFailResult("该房间暂不开放预定");
            }
            if (hotelHome.getHomeNum().equals("0")) {
                return ResultGenerator.genFailResult("该房暂无房间可定");
            }
            if (Integer.parseInt(hotelHome.getHomeNum()) <= list.size()) {
                return ResultGenerator.genFailResult("非常抱歉，您选择的日期已满房，请选择其他订房日期");
            }
            if (hotelHome.getOpenStart() != null && hotelHome.getOpenEnd() != null) {
                if ((CalendarUtil.strToDateYmd(hotelHome.getOpenStart()).getTime() <= CalendarUtil.strToDateYmd(startDate).getTime() && CalendarUtil.strToDateYmd(hotelHome.getOpenEnd()).getTime() >= CalendarUtil.strToDateYmd(startDate).getTime()) || (CalendarUtil.strToDateYmd(hotelHome.getOpenStart()).getTime() <= CalendarUtil.strToDateYmd(endDate).getTime() && CalendarUtil.strToDateYmd(hotelHome.getOpenEnd()).getTime() >= CalendarUtil.strToDateYmd(endDate).getTime())) {
                    return ResultGenerator.genFailResult("非常抱歉，您选择的日期已满房，请选择其他订房日期");
                }
            }

            String today = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
            String code = PayUtil.createCode(8);
            String out_trade_no = today + code;//商户订单号

            //HotelHome hotelHome = hotelHomeBiz.findById(hotelReservation.getHomeId());

            Date date1 = CalendarUtil.strToDate(startDate + " 14:00:00");
            Date date2 = CalendarUtil.strToDate(endDate + " 12:00:00");

            //Integer days = CalendarUtil.daysBetween(date1, date2);
            SysConfig sysConfig = sysConfigBiz.findById(1);

            Bill bill = new Bill();
            bill.setBillNo(out_trade_no);
            bill.setCustomerPayFee(Double.valueOf(sysConfig.getDeposit().toString()));
            bill.setPosFee(0D);
            bill.setBillType(0);
            bill.setBillFee(Double.valueOf(sysConfig.getDeposit().toString()));
            bill.setStatus(0);
            bill.setCustomerId(hotelReservation.getCustomerId());
            bill.setHotelId(hotelHome.getHotelId());
            bill.setHomeId(hotelHome.getId());
            bill.setExpiredTime((new Date(new Date().getTime() + 900000)));
            billBiz.save(bill);

            HotelReservation newHotelReservation = new HotelReservation();
            newHotelReservation.setBillId(bill.getId());
            newHotelReservation.setCustomerId(hotelReservation.getCustomerId());
            newHotelReservation.setHomeId(hotelHome.getId());
            newHotelReservation.setHotelId(hotelHome.getHotelId());
            newHotelReservation.setStatus(0);

            newHotelReservation.setReserveStartTime(CalendarUtil.strToDate(startDate + " 14:00:00"));
            newHotelReservation.setReserveEndTime(CalendarUtil.strToDate(endDate + " 12:00:00"));

            hotelReservationBiz.save(newHotelReservation);

            return ResultGenerator.genSuccessResult(bill.getId());
        }
    }


    @RequestMapping(value = "/isFull")
    public Result isFull(HotelReservation hotelReservation, @RequestParam String startDate, @RequestParam String endDate) throws Exception {
        ArrayList arrayList = new ArrayList();

        String date = startDate;
        HotelHome hotelHome = hotelHomeBiz.findById(hotelReservation.getHomeId());
        //如果房间数量为0 则返回全部满房
        if (hotelHome.getHomeNum().equals("0")) {
            return ResultGenerator.genSuccessResult(201, "当前房间无房可订");
        }

        while (CalendarUtil.strToDateYmd(date).getTime() <= CalendarUtil.strToDateYmd(endDate).getTime()) {
            if (hotelHome.getOpenStart() != null && hotelHome.getOpenEnd() != null) {
                //循环时间在关房区间内 则满足条件视为满房
                if ((CalendarUtil.strToDateYmd(hotelHome.getOpenStart()).getTime() <= CalendarUtil.strToDateYmd(date).getTime() && CalendarUtil.strToDateYmd(hotelHome.getOpenEnd()).getTime() >= CalendarUtil.strToDateYmd(date).getTime())) {
                    //满足条件 加入满房列表 日期+1 跳出本次循环进入下次循环
                    arrayList.add(date);
                    date = getAddDays(CalendarUtil.strToDateYmd(date), 1);
                    continue;
                }
            }

            //查询这个房间 startDate-endDate 所有被预约的数据
            Condition condition = new Condition(HotelReservation.class);
            condition.createCriteria().andEqualTo("homeId", hotelReservation.getHomeId()).andEqualTo("status", 1).andBetween("reserveStartTime", startDate, endDate);
            List<HotelReservation> list = hotelReservationBiz.findByCondition(condition);

            //房间数量 用来和已被预订房间数来对比 小于等于已被预订房间数即满房  大于即不满房
            Integer number = Integer.parseInt(hotelHome.getHomeNum());

            //已被预订房间数 循环满足条件+1 用来和房间数量作对比
            Integer rNumber = 0;

            for (Integer i = 0; i < list.size(); i++) {
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                //获取预约开始与结束时间年月日
                String bDate = formatter.format(list.get(i).getReserveStartTime());
                String eDate = formatter.format(list.get(i).getReserveEndTime());

                //如果循环时间 在预约开始与结束时间 区间内（开始时间当天是订房状态，结束时间当天不是订房状态，所以开始有= 结束没有=）则rNumber 已被预订房间数+1
                if (CalendarUtil.strToDateYmd(bDate).getTime() <= CalendarUtil.strToDateYmd(date).getTime() && CalendarUtil.strToDateYmd(eDate).getTime() > CalendarUtil.strToDateYmd(date).getTime()) {
                    rNumber = rNumber + 1;
                }
            }
            //循环结束 房间数量小于等于已被预订房间数即满房 即满房
            if (number <= rNumber) {
                //满足条件 加入满房列表 日期+1 跳出本次循环进入下次循环
                arrayList.add(date);
                date = getAddDays(CalendarUtil.strToDateYmd(date), 1);
                continue;
            }

            date = getAddDays(CalendarUtil.strToDateYmd(date), 1);
        }


        return ResultGenerator.genSuccessResult(arrayList);
    }
}
